<template>
  <div class="chart-container">
    <div ref="chartRef" class="chart" v-loading="loading"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { useModulesStore } from '@/stores/modules'
import { getChartThemeOptions, watchThemeChange } from '@/utils/chartTheme'

const modulesStore = useModulesStore()
const chartRef = ref(null)
const loading = ref(true)
const themeObserver = ref(null)
let chartInstance = null

const initChart = () => {
  if (!chartRef.value) return

  // 确保容器有正确的尺寸
  const container = chartRef.value
  if (container.clientWidth === 0 || container.clientHeight === 0) {
    // 如果容器尺寸为0，延迟重试
    setTimeout(() => {
      initChart()
    }, 100)
    return
  }

  // 如果已经存在实例，先销毁它
  if (chartInstance && !chartInstance.isDisposed()) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(chartRef.value)

  // 基于真实模块数据计算复杂度分布
  const modules = modulesStore.modules
  const complexityRanges = [
    { min: 0, max: 20, label: '0-20', color: '#67C23A' },
    { min: 21, max: 40, label: '21-40', color: '#E6A23C' },
    { min: 41, max: 60, label: '41-60', color: '#409EFF' },
    { min: 61, max: 80, label: '61-80', color: '#F56C6C' },
    { min: 81, max: 100, label: '81-100', color: '#FF4757' }
  ]

  // 计算每个复杂度范围的模块数量
  const complexityData = complexityRanges.map(range => {
    const count = modules.filter(module => {
      const complexity = module.complexity || 20 // 默认基础复杂度
      return complexity >= range.min && complexity <= range.max
    }).length
    return {
      range: range.label,
      count: count,
      color: range.color
    }
  })

  // 获取主题配置
  const themeConfig = getChartThemeOptions()

  const option = {
    backgroundColor: themeConfig.backgroundColor,
    title: {
      text: '模块复杂度分布',
      textStyle: {
        fontSize: 16,
        fontWeight: 600,
        color: themeConfig.textColor
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      backgroundColor: themeConfig.tooltip.backgroundColor,
      borderColor: themeConfig.tooltip.borderColor,
      textStyle: {
        color: themeConfig.tooltip.textStyle.color
      },
      formatter: (params) => {
        const data = params[0]
        return `${data.name}<br/>模块数量: ${data.value}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
      borderColor: themeConfig.grid.borderColor
    },
    xAxis: {
      type: 'category',
      data: complexityData.map(item => item.range),
      name: '复杂度范围',
      axisLine: themeConfig.xAxis.axisLine,
      axisTick: themeConfig.xAxis.axisTick,
      axisLabel: {
        ...themeConfig.xAxis.axisLabel,
        formatter: '{value}'
      },
      splitLine: themeConfig.xAxis.splitLine
    },
    yAxis: {
      type: 'value',
      name: '模块数量',
      axisLine: themeConfig.yAxis.axisLine,
      axisTick: themeConfig.yAxis.axisTick,
      axisLabel: {
        ...themeConfig.yAxis.axisLabel,
        formatter: '{value}'
      },
      splitLine: themeConfig.yAxis.splitLine
    },
    series: [
      {
        name: '模块数量',
        type: 'bar',
        data: complexityData.map(item => ({
          value: item.count,
          itemStyle: {
            color: item.color
          }
        })),
        barWidth: '60%'
      }
    ]
  }

  chartInstance.setOption(option)
}

// 更新图表数据
const updateChartData = () => {
  if (!chartInstance || chartInstance.isDisposed()) return

  // 基于真实模块数据计算复杂度分布
  const modules = modulesStore.modules
  const complexityRanges = [
    { min: 0, max: 20, label: '0-20', color: '#67C23A' },
    { min: 21, max: 40, label: '21-40', color: '#E6A23C' },
    { min: 41, max: 60, label: '41-60', color: '#409EFF' },
    { min: 61, max: 80, label: '61-80', color: '#F56C6C' },
    { min: 81, max: 100, label: '81-100', color: '#FF4757' }
  ]

  // 计算每个复杂度范围的模块数量
  const complexityData = complexityRanges.map(range => {
    const count = modules.filter(module => {
      const complexity = module.complexity || 20 // 默认基础复杂度
      return complexity >= range.min && complexity <= range.max
    }).length
    return {
      range: range.label,
      count: count,
      color: range.color
    }
  })

  // 只更新数据系列
  chartInstance.setOption({
    series: [{
      data: complexityData.map(item => ({
        value: item.count,
        itemStyle: {
          color: item.color
        }
      }))
    }]
  })
}

// 监听模块数据变化
watch(() => modulesStore.modules, (newModules) => {
  if (newModules && newModules.length > 0 && chartInstance && !chartInstance.isDisposed()) {
    // 只重新计算数据并更新图表，而不是重新初始化整个图表
    updateChartData()
  }
}, { deep: true })

onMounted(() => {
  setTimeout(() => {
    loading.value = false

    // 使用 nextTick 确保 DOM 完全渲染
    nextTick(() => {
      initChart()
    })

    // 监听窗口大小变化
    window.addEventListener('resize', () => {
      if (chartInstance) {
        chartInstance.resize()
      }
    })

    // 监听主题变化
    themeObserver.value = watchThemeChange(() => {
      if (chartInstance && !chartInstance.isDisposed()) {
        // 重新初始化图表以应用新主题
        initChart()
      }
    })
  }, 1000) // 增加延迟时间
})

onUnmounted(() => {
  // 清理图表实例
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }

  // 清理主题观察者
  if (themeObserver.value) {
    themeObserver.value.disconnect()
    themeObserver.value = null
  }

  // 清理事件监听器
  window.removeEventListener('resize', () => {
    if (chartInstance) {
      chartInstance.resize()
    }
  })
})
</script>

<style scoped lang="scss">
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 300px;

  .chart {
    width: 100%;
    height: 100%;
    min-height: 300px;
  }
}
</style>